export default {
  isPronunciationAvailable(word) {
    if (!word) return false;
    return !!(word.uk_speech || word.us_speech);
  },

  async playPronunciation(word, type, messageHandler) {
    if (!word) return { success: false, error: 'No word provided' };

    try {
      let audioPath;
      if (type === 'uk' && word.uk_speech) {
        audioPath = word.uk_speech;
      } else if (type === 'us' && word.us_speech) {
        audioPath = word.us_speech;
      } else {
        // Fallback to any available pronunciation
        audioPath = word.uk_speech || word.us_speech;
      }

      // Remove extra quotes and escape characters from the audio path
      if (audioPath) {
        // Remove surrounding quotes if present
        if (audioPath.startsWith('"') && audioPath.endsWith('"')) {
          audioPath = audioPath.slice(1, -1);
        }

        // Fix escaped forward slashes
        audioPath = audioPath.replace(/\\\//g, '/');

        // Create a new audio element and play
        const audio = new Audio(audioPath);
        await audio.play();
        
        if (messageHandler && messageHandler.success) {
          messageHandler.success('开始播放发音');
        }
        
        return { success: true };
      } else {
        if (messageHandler && messageHandler.warning) {
          messageHandler.warning('没有可用的发音文件');
        }
        return { success: false, error: 'No audio file available' };
      }
    } catch (err) {
      console.error('Error in playPronunciation:', err);
      if (messageHandler && messageHandler.error) {
        messageHandler.error('播放失败: ' + err.message);
      }
      return { success: false, error: err.message };
    }
  },

  stopPronunciation(audioElement) {
    try {
      if (audioElement) {
        audioElement.pause();
        audioElement.currentTime = 0;
        return { success: true };
      }
      return { success: false, error: 'No audio element provided' };
    } catch (err) {
      console.error('Error stopping pronunciation:', err);
      return { success: false, error: err.message };
    }
  }
};